package utils

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"strings"
)

var jwtSecret = []byte("bGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")



type Claims struct {
	Uid string
	jwt.StandardClaims
}

func NewClaims(uid string)*Claims{
	return &Claims{
		Uid:uid,
	}
}

func (c *Claims) GenerateToken() (string, error) {
	//c.ExpiresAt = time.Now().Add(24 * time.Hour).Unix()
	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}

func ParseHeaderToken(token string) (*Claims, error) {
	tokenArr := strings.Split(token, "Bearer ")
	if len(tokenArr) != 2 {
		return &Claims{}, errors.New("no Bearer found in header")
	}
	token = tokenArr[1]
	if token == "" {
		return &Claims{}, errors.New("no token string found in Bearer")
	}

	claims, err := ParseToken(token)
	if err != nil {
		return &Claims{}, err
	}
	return claims, nil
}


func GetHeaderClaims(c *gin.Context) (*Claims, error) {
	token := c.GetHeader("Authorization")
	if token == "" {
		return &Claims{}, errors.New("token not found in header")
	}

	claims, err := ParseHeaderToken(token)
	if err != nil {
		return &Claims{}, err
	}

	return claims, nil
}

func SetHeaderClaims(c *gin.Context,cl *Claims)error{
	token,err := cl.GenerateToken()
	if err !=nil{
		logrus.Errorf("gen token error: %s",err.Error())
		return err
	}
	c.Header("Authorization", fmt.Sprintf("Bearer %v", token))
	return nil
}